#include "CSavedInfo.h"
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;

CSavedInfo* CSavedInfo::m_nInstance = NULL;

CSavedInfo::CSavedInfo(void)
{
}

CSavedInfo::~CSavedInfo(void)
{
}

CSavedInfo* CSavedInfo::GetInstance()
{
	if(m_nInstance==NULL)
		m_nInstance = new CSavedInfo;
	return m_nInstance;
}

void CSavedInfo::StartTime(string szName, LARGE_INTEGER StartTime)
{
	bool tempIsThere = false;
	if(m_vProfilerData.size() != 0)
	{
		for(int i = 0; i <= m_vProfilerData.size()-1; ++i)
		{
			if((m_vProfilerData[i].GetName().compare(szName)) == 0)
			{
				m_vProfilerData[i].SetStart(StartTime);
				tempIsThere = true;
				break;
			}
		}
	}

	if(tempIsThere == false)
	{
		sCodeProfileData tempProfile;
		tempProfile.SetName(szName);
		tempProfile.SetStart(StartTime);
		tempProfile.SetTotalTimes(0);
		m_vProfilerData.push_back(tempProfile);
	}
}
void CSavedInfo::StopTime(string szName, LARGE_INTEGER StopTime)
{
	for(int i = 0; i <= m_vProfilerData.size()-1; ++i)
	{
		if((m_vProfilerData[i].GetName().compare(szName)) == 0)
		{
			double Elapsed = 0.0;
			Elapsed = (float)(StopTime.QuadPart - m_vProfilerData[i].GetStart().QuadPart) / (float)(GetFreq().QuadPart * 1000);
			m_vProfilerData[i].SetTotalTimes(m_vProfilerData[i].GetTotalTimes() + 1);
			m_vProfilerData[i].AddTime(Elapsed);
		}
	}
}

void CSavedInfo::SaveProfilerData()
{
	SYSTEMTIME st;
	GetLocalTime(&st);

	double tempAverage = 0;

	for(int i = 0; i <= m_vProfilerData.size()-1; ++i)
	{
		string tempString = "Resource/data/";
		tempString.append(m_vProfilerData[i].GetName() + ".txt");
		fstream ProfilerOutput(tempString.c_str(), ios::out);

		ProfilerOutput << "Profile for: " << m_vProfilerData[i].GetName() << endl;
		ProfilerOutput << "Date: " << st.wMonth << " : " << st.wDay << " : " << st.wYear
			<< "\nDay Of The Week: " << st.wDayOfWeek
			<< "\nTime: " << st.wHour << ":" << st.wMinute << "\n-----------------------------------------------\n\n";
		for(int j = 0; j <= m_vProfilerData[i].GetAll().size()-1; ++j)
		{
			tempAverage += m_vProfilerData[i].GetAll()[j];
			ProfilerOutput << m_vProfilerData[i].GetAll()[j] << endl;
		}

		ProfilerOutput << "-----------------------------------------------\n\n";
		ProfilerOutput << "Total Number of Times Called: " << m_vProfilerData[i].GetTotalTimes() << "\n\n";
		ProfilerOutput << "Average Time: " << tempAverage / m_vProfilerData[i].GetTotalTimes();
		ProfilerOutput.close();
	}
}
